package zld369504.tw.m_team.fragments;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Html;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.squareup.picasso.Transformation;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;

import java.util.List;

import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.FlowableEmitter;
import io.reactivex.FlowableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import zld369504.tw.m_team.R;
import zld369504.tw.m_team.ShowImageActivity;
import zld369504.tw.m_team.api.MTeamHttpsApiImpl;
import zld369504.tw.m_team.dao.TorrentDetail;
import zld369504.tw.m_team.widget.GroupLayout;

public class TorrentDescriptionFragment extends BaseFragment {

    public static final String TAG = "TorrentDescriptionFragment";

    private TorrentDetail detail;

    private LinearLayout llContent;

    public static TorrentDescriptionFragment getInstance(TorrentDetail detail) {
        TorrentDescriptionFragment fragment = new TorrentDescriptionFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("detail", detail);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            detail = (TorrentDetail) bundle.getSerializable("detail");
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_torrent_description, container, false);
        llContent = rootView.findViewById(R.id.llContent);
        return rootView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (detail != null && !TextUtils.isEmpty(detail.getDescription())) {
            Flowable.create(new FlowableOnSubscribe<Description>() {
                @Override
                public void subscribe(FlowableEmitter<Description> emitter) throws Exception {
                    Document document = Jsoup.parse(detail.getDescription());
                    document.setBaseUri(MTeamHttpsApiImpl.baseUrl);
                    parseData(document.body(), emitter);
                    emitter.onComplete();
                }
            }, BackpressureStrategy.DROP)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<Description>() {
                        @Override
                        public void accept(final Description description) throws Exception {
                            if (description.type == 1) {
                                GroupLayout.Params gpp = new GroupLayout.Params();
                                gpp.titleText = getResources().getString(R.string.Quote);
                                gpp.titleTextColor = Color.BLACK;
                                gpp.borderColor = Color.BLACK;
                                GroupLayout layout = new GroupLayout(getActivity(), gpp);
                                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                                layout.setLayoutParams(params);
                                layout.setPadding((int) TypedValue.applyDimension(
                                        TypedValue.COMPLEX_UNIT_DIP,
                                        8,
                                        getResources().getDisplayMetrics()),
                                        (int) TypedValue.applyDimension(
                                                TypedValue.COMPLEX_UNIT_DIP,
                                                20,
                                                getResources().getDisplayMetrics()),
                                        (int) TypedValue.applyDimension(
                                                TypedValue.COMPLEX_UNIT_DIP,
                                                8,
                                                getResources().getDisplayMetrics()),
                                        (int) TypedValue.applyDimension(
                                                TypedValue.COMPLEX_UNIT_DIP,
                                                8,
                                                getResources().getDisplayMetrics()));
                                TextView textView = new TextView(getActivity());
                                LinearLayout.LayoutParams textViewParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                                textView.setLayoutParams(textViewParams);
                                textView.setText(Html.fromHtml(description.htmlText.trim()));
                                layout.addView(textView);
                                llContent.addView(layout);
                            } else if (description.type == 2) {
                                ImageView imageView = new ImageView(getActivity());
                                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                                imageView.setLayoutParams(params);
                                imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
                                imageView.setAdjustViewBounds(true);
                                Picasso.with(getActivity()).load(description.url)
                                        .transform(getTransformation(imageView)).into(imageView);
                                imageView.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        Intent intent = new Intent(getActivity(), ShowImageActivity.class);
                                        intent.putExtra("URL", description.url);
                                        getActivity().startActivity(intent);
                                    }
                                });
                                llContent.addView(imageView);
                            } else if (description.type == 3) {
                                TextView textView = new TextView(getActivity());
                                LinearLayout.LayoutParams textViewParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                                textView.setLayoutParams(textViewParams);
                                textView.setText(Html.fromHtml(description.htmlText.trim()));
                                llContent.addView(textView);
                            }
                        }
                    });
        }
    }

    private void parseData(Node node, FlowableEmitter<Description> emitter) {
        for (Node node1 : node.childNodes()) {
            if (node1 instanceof TextNode) {
                Description textDescription = new Description();
                textDescription.htmlText = ((TextNode) node1).text().trim();
                textDescription.type = 3;
                emitter.onNext(textDescription);
            } else {
                String node1Name = node1.nodeName();
                switch (node1Name) {
                    case "fieldset"://quote
                        List<Node> cNodeList = node1.childNodes();
                        for (Node cNode : cNodeList) {
                            if (!(cNode instanceof TextNode)) {
                                if ("legend".equals(cNode.nodeName())) {
                                    cNode.remove();
                                    break;
                                }
                            }
                        }
                        Description quoteDescription = new Description();
                        quoteDescription.htmlText = node1.toString().trim();
                        quoteDescription.type = 1;
                        emitter.onNext(quoteDescription);
                        break;
                    case "img":
                        Description imageDescription = new Description();
                        imageDescription.url = node1.absUrl("src");
                        imageDescription.type = 2;
                        emitter.onNext(imageDescription);
                        break;
                    case "b":
                    case "span":
                    case "font":
                        //递归调用
                        parseData(node1,emitter);
                        break;
                    case "a":
                        if("faqlink".equals(node1.attr("class"))){
                            parseData(node1,emitter);
                        }
                        break;
                }
            }
        }
    }

    private static Transformation getTransformation(final ImageView view) {
        return new Transformation() {
            @Override
            public Bitmap transform(Bitmap source) {
                int targetWidth = view.getWidth();

                //返回原图
                if (source.getWidth() == 0 || source.getWidth() < targetWidth) {
                    return source;
                }

                //如果图片大小大于等于设置的宽度，则按照设置的宽度比例来缩放
                double aspectRatio = (double) source.getHeight() / (double) source.getWidth();
                int targetHeight = (int) (targetWidth * aspectRatio);
                if (targetHeight == 0 || targetWidth == 0) {
                    return source;
                }
                Bitmap result = Bitmap.createScaledBitmap(source, targetWidth, targetHeight, false);
                if (result != source) {
                    // Same bitmap is returned if sizes are the same
                    source.recycle();
                }
                return result;
            }

            @Override
            public String key() {
                return "transformation" + " desiredWidth";
            }
        };
    }

    class Description {
        String htmlText;
        int type;
        String url;
    }
}
